/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-09-09
 * Time: 11:56
 */

class Counter {
    int count;

    public void add() {
        count++;
    }

}
public class ThreadDemo {
    private static int val;

    public static void main1(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()-> {
            for (int i = 0; i < 100000; i++) {
                val++;
                // 注意循环里面不干其他事情的话,才能明显的看出 问题
                // 如果循环里面干其他事情的话, 就要耗时,就会导致两个线程 读取到同一个值的概率大大降低
//                 System.out.println("t1" + val);
            }
        });

        Thread t2 = new Thread(()-> {
            for (int i = 0; i < 100000; i++) {
                val++;
                // 注意循环里面不干其他事情的话,才能明显的看出 问题
                // 如果循环里面干其他事情的话, 就要耗时,就会导致两个线程 读取到同一个值的概率大大降低
//                 System.out.println("t2" + val);
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(val);
    }

    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(()-> {
            for (int i = 0; i < 100000; i++) {
                counter.add();
            }
        });

        Thread t2 = new Thread(()-> {
            for (int i = 0; i < 100000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(counter.count);
    }
}
